//
//  MyPresentationAnimationController.m
//  JiongTu
//
//  Created by 杨璟 on 16/4/25.
//  Copyright © 2016年 YSKJ. All rights reserved.
//

#import "MyPresentationAnimationController.h"

#import "UIView+Extension.h"

@interface MyPresentationAnimationController ()<UIViewControllerAnimatedTransitioning>

@property (nonatomic, assign) BOOL isPresenting;
@property (nonatomic, assign) NSTimeInterval duration;

@end

@implementation MyPresentationAnimationController

- (instancetype)initWithPresenting:(BOOL)presenting {
    if (self = [super init]) {
        _isPresenting = presenting;
    }
    return self;
}

- (NSTimeInterval)duration {
    if (!_duration) {
        _duration = 0.5;
    }
    return _duration;
}

- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext {
    return self.duration;
}

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext {
    if (self.isPresenting) {
        [self animatePresentationWithTransitionContext:transitionContext];
    } else {
        [self animateDismissalWithTransitionContext:transitionContext];
    }
}

- (void)animatePresentationWithTransitionContext:(id<UIViewControllerContextTransitioning>)transitionContext {
    
    UIViewController *presentedController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIView *presentedControllerView = [transitionContext viewForKey:UITransitionContextToViewKey];
    UIView *containerView = [transitionContext containerView];
    
    presentedControllerView.frame = [transitionContext finalFrameForViewController:presentedController];
    presentedControllerView.centerX -= containerView.width;
    
    [containerView addSubview:presentedControllerView];
    
    [UIView animateWithDuration:self.duration delay:0.0 usingSpringWithDamping:1.0 initialSpringVelocity:0.0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
        presentedControllerView.centerX += containerView.width;
    } completion:^(BOOL finished) {
        [transitionContext completeTransition:finished];
    }];
    
}

- (void)animateDismissalWithTransitionContext:(id<UIViewControllerContextTransitioning>)transitionContext {
    UIView *presentedControllerView = [transitionContext viewForKey:UITransitionContextFromViewKey];
    UIView *containerView = [transitionContext containerView];
    
    [UIView animateWithDuration:self.duration delay:0.0 usingSpringWithDamping:1.0 initialSpringVelocity:0.0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
        presentedControllerView.centerX += containerView.width;
    } completion:^(BOOL finished) {
        [transitionContext completeTransition:finished];
    }];
}

@end
